package swf;

class BitStream {
	var stream : Array<Int>;
	var offset : Int;
	
	public function new () {
		stream = new Array<Int>();
		offset = 0;
	}
	
	public function toString () : String {
		var s = "";
		for( byte in stream ) {
			s += String.fromCharCode( byte );
		}
		return s;
	}
	
	public function appendInt ( n : Int, length : Int, ?signed : Bool ) : Void {
		var bits : Int;
		if( signed == true ) {
			bits = ( (((n < 0) ? 1 : 0) << (length - 1)) | (n & (-1 >> (33 - length))) );
		} else {
			bits = n & (-1 >> (32 - length));
		}
		
		var last = (offset == 0) ? 0 : stream.pop();
		while( length > (8 - offset ) ) {
			stream.push( last | (bits >> (length - (8 - offset))) );
			length -= 8 - offset;
			bits = bits & (-1 >> (32 - length));
			last = 0;
			offset = 0;
		}
		stream.push( ( last | (bits << ((8 - offset) - length)) ) & 0xff );
		offset = (offset + length) % 8;
	}
}
